Matrix Operations

Now that we've learned how to create a matrix, let's learn how to use functions and perform operations on it!

Run the following code to create the stock.matrix from earlier

In [18]:
# Prices
goog <- c(450,451,452,445,468)
msft <- c(230,231,232,236,228)

# Put vectors into matrix
stocks <- c(goog,msft)
stock.matrix <- matrix(stocks,byrow=TRUE,nrow=2)

# Name matrix
days <- c('Mon','Tue','Wed','Thu','Fri')
st.names <- c('GOOG','MSFT')
colnames(stock.matrix) <- days
rownames(stock.matrix) <- st.names

# Display
stock.matrix
Out[18]:
MonTueWedThuFri
GOOG450451452445468
MSFT230231232236228

We can perform functions across the columns and rows, such as colSum:

In [19]:
colSums(stock.matrix)
Out[19]:
Mon
680
Tue
682
Wed
684
Thu
681
Fri
696
In [20]:
# Doesn't really make sense for stocks, but just to show how it works
rowSums(stock.matrix)
Out[20]:
GOOG
2266
MSFT
1157

We can also do other mathematical operations, check this reference for all functions available.

In [21]:
rowMeans(stock.matrix)
Out[21]:
GOOG
453.2
MSFT
231.4

Binding columns and rows

Let's go ahead and see how we can add columns and rows to a matrix, we can use the cbind() to bind a new column, and rbind() to bind a new row. For example, let's bind a new row with Facebook stock:

In [22]:
FB <- c(111,112,113,120,145)
In [23]:
tech.stocks <- rbind(stock.matrix,FB)
In [24]:
tech.stocks
Out[24]:
MonTueWedThuFri
GOOG450451452445468
MSFT230231232236228
FB111112113120145

Now let's add an average column to the matrix:

In [25]:
avg <- rowMeans(tech.stocks)
In [26]:
avg
Out[26]:
GOOG
453.2
MSFT
231.4
FB
120.2
In [27]:
tech.stocks <- cbind(tech.stocks,avg)
In [28]:
tech.stocks
Out[28]:
MonTueWedThuFriavg
GOOG450.0451.0452.0445.0468.0453.2
MSFT230.0231.0232.0236.0228.0231.4
FB111.0112.0113.0120.0145.0120.2

Great! We've gone over some basic matrix operations! Up next we will talk about selecting and indexing matrix elements!